﻿using System;
using System.Data.Common;
using System.Data.SqlClient;

namespace DataAccessObjectLayer
{
    public class GetMax
    {
        /// <summary>
        /// getMax is for the primary key in the table
        /// </summary>
        /// <param name="query">The sql query.</param>
        /// <returns>Gets the maximum identifier in the database from a specific table.</returns>
        public static int GetMaxId(String query)
        {
            int id = -1;
            var dbCon = new DBCon();
            using (DbConnection con = dbCon.GetConnection())
            {
                con.Open();

                DbCommand comm = new SqlCommand(query, (SqlConnection)con);

                try
                {
                    int maxId = Convert.ToInt32(comm.ExecuteScalar());

                    if (maxId > id)
                    {
                        id = maxId;
                    }
                }
                catch (Exception)
                {
                    id = 0;
                }
            }
            return id;
        }
    }
}